package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.Setmeal;
import com.itheima.reggie.domain.SetmealDish;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询套餐 原生mybatis实现
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    /*@GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        Page<SetmealDto> pageInfo = setmealService.pageByName(page,pageSize,name);
        return R.success(pageInfo);
    }*/

    /**
     * 分页查询套餐 mybatisPlus实现
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
   /* @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //构建分页器
        Page<Setmeal> setmealPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //模糊查询
        lqw.like(StringUtils.isNotBlank(name),Setmeal::getName,name);
        //排序
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //查询原始数据
        setmealService.page(setmealPage,lqw);

        Page<SetmealDto> setmealDtoPage = new Page<>();
        //拷贝除records之外的数据到setmealDtoPage
        BeanUtils.copyProperties(setmealPage,setmealDtoPage,"records");
        //获取原始数据集
        List<Setmeal> records = setmealPage.getRecords();
        List<SetmealDto> list = records.stream().map(record -> {
            SetmealDto setmealDto = new SetmealDto();
            //拷贝数据
            BeanUtils.copyProperties(record, setmealDto);
            //获取套餐的分类id
            Long categoryId = record.getCategoryId();
            //获取套餐分类
            Category category = categoryService.getById(categoryId);
            //设置分类名称
            String categoryName = category.getName();
            if (categoryName!=null) {
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }*/

    /**
     * 分页查询套餐 优化sql
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //构造分页
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //模糊查询
        lqw.like(StringUtils.isNotBlank(name), Setmeal::getName, name);
        //排序
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //查询原始数据
        setmealService.page(setmealPage, lqw);

        Page<SetmealDto> setmealDtoPage = new Page<>();
        //拷贝除records之外的数据
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
        //获取原始数据集
        List<Setmeal> records = setmealPage.getRecords();
        //获取套餐分类的id集合
        Set<Long> set = records.stream().map(Setmeal::getCategoryId).collect(Collectors.toSet());
        //根据分类id集合获取分类集合
        List<Category> list = categoryService.listByIds(set);
        //List集合转为Map key:分类id value:分类名称
        Map<Long, String> map = list.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        List<SetmealDto> setmealDtoList = records.stream().map(record -> {
            SetmealDto setmealDto = new SetmealDto();
            //拷贝
            BeanUtils.copyProperties(record, setmealDto);
            //设置分类名称
            setmealDto.setCategoryName(map.get(record.getCategoryId()));
            return setmealDto;
        }).collect(Collectors.toList());
        //设置数据集
        setmealDtoPage.setRecords(setmealDtoList);
        return R.success(setmealDtoPage);
    }


    /**
     * 添加套餐及套餐菜品
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(cacheNames = "setmeal",allEntries = true)
    @PostMapping
    public R<String> saveWithDish(@RequestBody SetmealDto setmealDto) {
        log.info("新增套餐:{}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("添加成功");
    }

    /**
     * 根据ids批量停售/启售套餐
     *
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(cacheNames = "setmeal",allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status, Long[] ids) {
        List<Long> list = Arrays.stream(ids).collect(Collectors.toList());
        List<Setmeal> setmeals = setmealService.listByIds(list);
        setmeals.forEach(setmeal -> setmeal.setStatus(status));

        setmealService.updateBatchById(setmeals);
        return R.success("修改成功");
    }

    /**
     * 根据ids批量删除套餐
     *
     * @param ids
     * @return
     */
    @CacheEvict(cacheNames = "setmeal",allEntries = true)
    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids) {
        log.info("删除套餐的id:{}", ids);
        setmealService.deleteByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 根据id查询套餐信息
     *
     * @param id
     * @return
     */
    @Cacheable(cacheNames = "setmeal",key = "#id")
    @GetMapping("/{id}")
    public R<SetmealDto> getByIdWithDishes(@PathVariable Long id) {
        log.info("查询套餐的id:{}", id);
        SetmealDto setmealDto = setmealService.getByIdWithDishes(id);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐信息
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(cacheNames = "setmeal",allEntries = true)
    @PutMapping
    public R<String> updateWithDishes(@RequestBody SetmealDto setmealDto){
        setmealService.updateWithDishes(setmealDto);
        return R.success("修改成功");
    }

    /**
     * 查询套餐数据
     *
     * @param setmeal
     * @return
     */
    @Cacheable(cacheNames = "setmeal",key = "#setmeal.categoryId+'_'+#setmeal.status")
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Setmeal::getStatus,1);
        lqw.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        lqw.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(lqw);
        return R.success(list);
    }
    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;
    /**
     * 展示套餐菜品
     *
     * @param id
     * @return
     */
    @Cacheable(cacheNames = "setmeal",key = "'dish_'+#id+'_1'")
    @GetMapping("/dish/{id}")
    public R<List> getDishes(@PathVariable Long id){
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishes = setmealDishService.list(lqw);
        List<DishDto> list = setmealDishes.stream().map(setmealDish -> {
            Long dishId = setmealDish.getDishId();
            Dish dish = dishService.getById(dishId);
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            dishDto.setCopies(setmealDish.getCopies());
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(list);
    }
}
